package com.futao.springboot.learn.redis.cj;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author futao@gmail.com
 * @date 2021/11/22
 */
@Slf4j
@Component
public class Cj implements ApplicationRunner {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY = "test:set:cj";
    /**
     * 奖品数
     */
    private static final int COUNT = 10000;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String[] idArr = IntStream.rangeClosed(1, COUNT).mapToObj(String::valueOf).collect(Collectors.toList()).toArray(new String[]{});
        log.info("生成的id：{}", Arrays.toString(idArr));
        redisTemplate.opsForSet().add(KEY, idArr);
        log.info("数据准备完毕:{}", redisTemplate.opsForSet().size(KEY));

        //模拟并发用户为2W
        CyclicBarrier cyclicBarrier = new CyclicBarrier(COUNT * 2);
        for (int i = 0; i < COUNT * 2; i++) {
            new Thread(() -> {
                try {
                    log.info("准备好了");
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                log.info("当前线程获取到的值为:{}", redisTemplate.opsForSet().pop(KEY));
            }, "consumer-" + i + 1).start();
        }

    }
}
